package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishCategoryVO;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;



    /**
     * 新增菜品和口味
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {

        // 新增菜品基础信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);

        // insert成功时，将 其id值 赋给了dish实体类的id属性
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors.size() != 0 && flavors != null) {

            // 空的口味，要排除掉
            for (int i = 0; i < flavors.size(); i++) {
                if (flavors.get(i).getValue().length() == 2) {
                    flavors.remove(i);
                    i--;
                }
            }

            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            // 新增口味
            dishFlavorMapper.insert(flavors);
        }


    }

    /**
     * 分页查询菜品列表
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 删除菜品
     *
     * @param ids
     */
    @Transactional
    @Override
    public void delete(List<Long> ids) {

        // 起售中的菜品不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getInfoById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 被套餐关联的菜品不能删除
        List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealIdsByDishIds(ids);

        if (setmealDishList.size() != 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 删除菜品后，关联的口味数据也需要删除
        // 删除菜品
        dishMapper.delete(ids);
        // 删除关联的口味数据
        for (Long id : ids) {
            dishFlavorMapper.delete(id);
        }


    }

    /**
     * 根据id查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getInfoByid(Long id) {

        // 查询菜品信息
        Dish dish = dishMapper.getInfoById(id);

        // 查询对应的口味信息
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getInfoByDishId(id);

        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);

        return dishVO;
    }

    /**
     * 修改菜品信息和对应的口味信息
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 修改菜品信息
        dishMapper.update(dish);

        // 修改菜品对应的口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();

        // 有填写口味信息才更改
        if (flavors.size() != 0) {
            Long dishID = dish.getId();
            // 删除对应的口味信息
            dishFlavorMapper.delete(dishID);

            // 空的口味，要排除掉
            for (int i = 0; i < flavors.size(); i++) {
                if (flavors.get(i).getValue().length() == 2) {
                    flavors.remove(i);
                    i--;
                }
            }

            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishID);
            }

            // 新增口味信息
            dishFlavorMapper.insert(flavors);
        }


    }


    /**
     * 根据分类ID查询菜品信息
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishCategoryVO> getInfoByCategoryId(Long categoryId) {
        List<DishCategoryVO> dishCategoryVOList = dishMapper.getInfoByCategoryId(categoryId);

        return dishCategoryVOList;
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);

            List<SetmealDish> setmeals = setmealDishMapper.getSetmealIdsByDishIds(dishIds);

            if (setmeals != null && setmeals.size() > 0) {
                for (SetmealDish s : setmeals) {
                    Setmeal setmeal = Setmeal.builder().id(s.getSetmealId()).status(StatusConstant.DISABLE).build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getInfoByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
